using HelpDeskTool.Entities;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using HelpDeskTool.Views;

namespace HelpDeskTool;

partial class MainWindow : Window
{
	private readonly ViewModel viewModel;

	public MainWindow(ViewModel viewModel, ILogger<MainWindow> logger)
	{
		InitializeComponent();

		this.viewModel = viewModel;
		DataContext = this.viewModel;
	}

	private void ConnectToComputer(string hostname)
	{
		try
		{
			if (rbMsra.IsChecked == true)
				Process.Start("msra.exe", $"/offerRA {hostname}");
			else
				Process.Start("mstsc.exe", $"/f /v:{hostname}");
		}
		catch (Exception ex)
		{
			MessageBox.Show(ex.Message);
		}
	}

	private void ConnectToSelectedComputer()
	{
		if (lvComputers.SelectedItem is IComputer computer)
			ConnectToComputer(computer.Name);
	}

	private void ListViewItem_MouseDoubleClick(object sender, MouseButtonEventArgs e) => ConnectToSelectedComputer();

	private void txtFilter_TextChanged(object sender, TextChangedEventArgs e)
	{
		viewModel.Filter = txtFilter.Text.Trim();
		viewModel.ApplyFilter();
		lvComputers.SelectedIndex = 0;
	}

	private void txtFilter_KeyDown(object sender, KeyEventArgs e)
	{
		if (e.Key == Key.Enter)
			ConnectToSelectedComputer();
	}

	private void imgRemove_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
	{
		txtFilter.Clear();
		txtFilter.Focus();
	}

	private void Window_KeyDown(object sender, KeyEventArgs e) => txtFilter.Focus();

	private void lvComputers_Click(object sender, RoutedEventArgs e)
	{
		var columnName = (e.OriginalSource as GridViewColumnHeader)?.Name;

		if (!string.IsNullOrWhiteSpace(columnName))
			viewModel.Sort(columnName);
	}
}
